﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QLZJFurnitureSCM.Model;
using System.Data.SqlClient;
using System.Data;
using System.Data.Linq;

namespace QLZJFurnitureSCM.DAL
{
    public class ProductPriceChangeDAO:IBaseDAO<ProductPriceChange>
    {
        private SqlConnection sqlConn = null;
        //private SqlDataAdapter adapter = null;

        private string connectionString = DALFactory.CONNECTIONSTRING;

        public ProductPriceChangeDAO()
        {
            sqlConn = new SqlConnection(connectionString);
        }

        public ProductPriceChange Create(ProductPriceChange t)
        {
            try
            {
                string query = string.Format("insert into ProductPriceChange([productName],[productPrice],[productPriceNow],[productChangeDate],[productChangeBy],[productId]) values ('{0}',{1},{2},'{3}','{4}',{5}); select @@identity;", 
                    t.ProductName, t.ProductPrice, t.ProductPriceNow, t.ProductChangeDate, t.ProductChangeBy, t.ProductId);
                if (sqlConn.State != ConnectionState.Open)
                    sqlConn.Open();
                SqlCommand sqlCmd = new SqlCommand(query, sqlConn);
                Console.WriteLine(query);
                object o = sqlCmd.ExecuteScalar();
                sqlConn.Close();
                if (o != null)
                    t.ChangeId = int.Parse(o.ToString());
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex);
                return Create(t);
            }
            return t;
            
        }

        public ProductPriceChange Read(ProductPriceChange t)
        {
            throw new NotImplementedException();
        }

        public bool Update(ProductPriceChange t)
        {
            throw new NotImplementedException();
        }

        public bool Delete(ProductPriceChange t)
        {
            throw new NotImplementedException();
        }

        public List<ProductPriceChange> ReadAll()
        {
            DataContext dataContext = null;
            IEnumerable<ProductPriceChange> enumProductPriceChange = null;
            try
            {
                dataContext = new DataContext(connectionString);
                enumProductPriceChange = dataContext.ExecuteQuery<ProductPriceChange>("select * from ProductPriceChange;");
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("ex: " + ex.Message);
                return null;
            }
            return enumProductPriceChange.ToList();
        }
    }
}
